PHPology is a collective of highly skilled, award winning, web gurus.
Contact Raj on 07985 467 213 or email [email protected]
PHP Simple_XML with namespaces
Had to read in an external RSS file from T3 and needed to drill into the "content" node which had a namespace. Using traditional ways of echoing out this node was not working so searching the net found a nice simple solution.
Below is the code to loop thru the "items" node without the name namespace involved:
<?php $url = "http://best-apps.t3.com/category/platforms/android/feed/"; //download the feed from t3 with fopen $handle = fopen($url, "r"); while (!feof($handle)) { $contents .= fread($handle, 8192); } fclose($handle); //echo $contents; $xml = simplexml_load_string($contents); //print_r($xml); echo "
- "; $i = 0; foreach($xml->channel->item as $item) { $alt_bg = (fmod($i, 2)) ? "bg-alt-even" : "bg-alt-odd"; //alternative background colour thing ?>
- <?php echo $item->title?> <?php $i++; } echo "
Below code includes the way I drilled into the namespace for "content:encoded"
<?php $url = "http://best-apps.t3.com/category/platforms/android/feed/"; //download the feed from t3 with fopen $handle = fopen($url, "r"); while (!feof($handle)) { $contents .= fread($handle, 8192); } fclose($handle); //echo $contents; $xml = simplexml_load_string($contents); //print_r($xml); echo "
- "; $i = 0; foreach($xml->channel->item as $item) { $alt_bg = (fmod($i, 2)) ? "bg-alt-even" : "bg-alt-odd"; //alternative background colour thing //Use that namespace from "content" $namespaces = $item->getNameSpaces(true); $content = $item->children($namespaces['content']); echo $content->encoded; ?>
- <?php echo $item->title?> <?php $i++; } echo "
The code reference is just a mock up and will need cleaning up but gives you an idea at least.